<template>
  <div ref="sceneContainer" class="scene-container"></div>
</template>

<script setup>
  import { ref, onMounted, onUnmounted } from 'vue'
  import * as THREE from 'three'
  import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'

  const sceneContainer = ref(null)

  let scene, camera, renderer, mesh

  // 初始化场景
  function initScene() {
    // 创建场景
    scene = new THREE.Scene()

    // 创建相机
    camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
    camera.position.z = 5

    // 创建渲染器
    renderer = new THREE.WebGLRenderer({ antialias: true })
    renderer.setSize(window.innerWidth, window.innerHeight)
    renderer.setClearColor(0xf0f0f0) // 设置背景颜色

    // 将渲染器的 DOM 元素挂载到容器上
    sceneContainer.value.appendChild(renderer.domElement)

    // 添加控制器，允许用户旋转和缩放视角
    const controls = new OrbitControls(camera, renderer.domElement)
    controls.enableDamping = true
    controls.dampingFactor = 0.05
  }

  // 创建 3D 图片
  function createImage() {
    // 创建一个平面几何体
    const geometry = new THREE.PlaneGeometry(2, 2)

    // 创建一个纹理加载器
    const textureLoader = new THREE.TextureLoader()

    // 加载图片并创建材质
    const material = new THREE.MeshBasicMaterial({
      map: textureLoader.load('https://example.com/your-image.jpg') // 替换为你的图片 URL
    })

    // 创建一个网格对象
    mesh = new THREE.Mesh(geometry, material)
    scene.add(mesh)
  }

  // 动画循环
  function animate() {
    requestAnimationFrame(animate)

    // 旋转图片
    mesh.rotation.y += 0.01

    // 渲染场景
    renderer.render(scene, camera)
  }

  onMounted(() => {
    initScene()
    createImage()
    animate()

    // 处理窗口大小变化
    window.addEventListener('resize', onWindowResize)
  })

  onUnmounted(() => {
    // 移除事件监听器
    window.removeEventListener('resize', onWindowResize)

    // 清理资源
    renderer.dispose()
    renderer.forceContextLoss()
    renderer.domElement.remove()
  })

  // 窗口大小变化时调整相机和渲染器
  function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight
    camera.updateProjectionMatrix()
    renderer.setSize(window.innerWidth, window.innerHeight)
  }
</script>

<style>
  .scene-container {
    width: 100vw;
    height: 100vh;
    margin: 0;
    overflow: hidden;
  }
</style>
